package proxyPool

import (
	IP "ahutoj/web/service/originJudge/proxyPool/ip"
	"ahutoj/web/utils"
	"context"
	"fmt"
	"net/http"
	"sync"
	"time"
)
func GetIpURL(ip *IP.IP) string {
	if ip.ProxyType == "https" {
		return fmt.Sprintf("https://%s:%d", ip.ProxyHost, ip.ProxyPort)
	} else {
		return fmt.Sprintf("http://%s:%d", ip.ProxyHost, ip.ProxyPort)
	}
}

// CheckIp is to check the ip work or not
func CheckIp(ctx context.Context, ip *IP.IP) bool {
	// 检测代理iP访问地址
	var testIp string
	var testUrl string
	if ip.ProxyType == "https" {
		testIp = fmt.Sprintf("https://%s:%d", ip.ProxyHost, ip.ProxyPort)
		testUrl = "https://codeforces.com/"
	} else {
		testIp = fmt.Sprintf("http://%s:%d", ip.ProxyHost, ip.ProxyPort)
		testUrl = "http://codeforces.com/"
	}
	// 创建连接客户端
	httpClient := &http.Client{}
	utils.ConfigureClient(httpClient, func(c *http.Client) {
		utils.WithProxy(c, testIp)
	})
	begin := time.Now() //判断代理访问时间
	// 使用代理IP访问测试地址
	res, err := httpClient.Get(testUrl)
	if err != nil {
		// logger.Warnf("testIp: %s, testUrl: %s: error msg: %v", testIp, testUrl, err.Error())
		return false
	}

	defer res.Body.Close()
	if res.StatusCode == http.StatusOK {
		// 判断是否成功访问，如果成功访问StatusCode应该为200
		speed := time.Since(begin).Nanoseconds() / 1000 / 1000 //ms
		ip.ProxySpeed = int(speed)
		IP.UpdateIp(ctx, ip)
		return true
	}
	return false
}

// CheckProxyDB to check the ip in DB
func CheckProxyDB(ctx context.Context) {
	ips := IP.GetAllIp(ctx)

	var wg sync.WaitGroup
	for _, v := range ips {
		wg.Add(1)
		go func(ip IP.IP) {
			if !CheckIp(ctx, &ip) {
				IP.DeleteIp(ctx, &ip)
			}
			wg.Done()
		}(v)
		time.Sleep(5*time.Second)
	}
	wg.Wait()
	time.Sleep(300 * time.Second)
}

// CheckProxy .
func CheckProxy(ctx context.Context, ip *IP.IP) {
	if CheckIp(ctx, ip) {
		IP.SaveIp(ctx, ip)
	}
}